package es

import (
	"strings"
	"time"
	"github.com/gogf/gf/encoding/gurl"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/container/gmap"
	"github.com/olivere/elastic/v7"
)

type EsClient struct {
	rawClient      *elastic.Client
}

var (
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "default"
)

func New(name string) *EsClient {
	// 获取es配置
	host := g.Cfg().GetString(name + ".host")
	port := g.Cfg().GetString(name + ".port")
	user := g.Cfg().GetString(name + ".user")
	pass := g.Cfg().GetString(name + ".pass")
	check := g.Cfg().GetBool(name + ".check")
	hosts := []string{}
	for _, h := range strings.Split(host, ",") {
		if strings.Contains(h, "http://") == false {
			h = "http://" + strings.Trim(h, " ")
		}
		u, _ := gurl.ParseURL(h, 4)
		if u["post"] == "" && port != "" {
			h = h + ":" + port
		}
		hosts = append(hosts, h)
	}
	//默认选择7.0版本
	// 连接客户端 注意es版本必须和包的版本一致
	rawClient, err := elastic.NewClient(
		elastic.SetURL(hosts...),
		elastic.SetSniff(false),
		elastic.SetHealthcheck(check),
		elastic.SetHealthcheckInterval(10 * time.Second),
		elastic.SetGzip(true),
		elastic.SetBasicAuth(user, pass),
	)
	if err != nil {
		// Handle error
		panic(err)
	}
	client := &EsClient{
		rawClient: rawClient,
	}
	return client
}

// 容器封装
func Instance(name ...string) *EsClient {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = "elasticsearch.config." + name[0]
	} else {
		key = "elasticsearch.config." + key
	}
	return instances.GetOrSetFunc(key, func() interface{} {
		return New(key)
	}).(*EsClient)
}

// 客户端示例
func Client(name ...string) *EsClient {
	return Instance(name...)
}
